<template>
  <div
    id="carPredition"
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
  >
    <el-row>
      <div id="reportrange" class="form-control">
        <el-col :xs="24" :sm="24" :lg="24" class="toFlex">
          <label for="cascader" >选择项目:</label>
          <el-cascader
            clearable
            placeholder="请选择"
            :options="selector"
            filterable
            :show-all-levels="false"
            :collapse-tags="true"
            v-model="selected"
            @change="changeProject"
            :props="props"
            style="margin-left: 10px; width:15%"
            id="cascader"
            >
          </el-cascader>
          <label for="select" style="margin-left:10%">销售:</label>
          <el-select
            v-model="sale"
            multiple
            @change="filterData($event,'销售')"
            @focus="getOptions1('销售')"
            placeholder="请选择"
            collapse-tags
            clearable
            filterable
            style="margin-left: 10px; width:15%">
            <el-option
              v-for="item in saleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
          
         </el-col>
           
         <el-col :xs="24" :sm="24" :lg="24" class="toFlex" style="margin:10px 0 10px 0px">  
          <label for="select">合同状态:</label>
          <el-select
            v-model="agreementStatus"
            multiple
            @change="filterData($event,'合同状态')"
            @focus="getOptions1('合同状态')"
            placeholder="请选择"
            collapse-tags
            clearable
            filterable
            style="margin-left: 10px; width:15%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
          <label for="select" style="margin-left:10%">客户经理:</label>
          <el-select
            v-model="costumeMg"
            multiple
            @change="filterData($event,'客户经理')"
            @focus="getOptions1('客户经理')"
            placeholder="请选择"
            collapse-tags
            clearable
            filterable
            style="margin-left: 10px; width:15%">
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
          </el-col>
          
          <label for="select">正式项目/潜在项目概率:</label>
          <el-select
            v-model="proStatus"
            multiple
            @change="handleChange3($event)"
            placeholder="请选择"
            collapse-tags
            clearable
            filterable
            style="margin-left: 10px">
            <el-option
              v-for="item in cusNamesOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
          <label for="select" style="margin-left:5%">主技术/产品中心:</label>
          <el-select
            v-model="Produnction"
            multiple
            @change="filterData($event,'主技术中心/主产品中心')"
            @focus="getOptions1('主技术中心/主产品中心')"
            placeholder="请选择"
            collapse-tags
            clearable
            filterable
            style="margin-left: 10px">
            <el-option
              v-for="item in ProdunctionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>
        <label for="select" style="margin-left:5%">客户部门:</label>
          <el-select
            v-model="cusDept"
            multiple
            @change="filterData($event,'客户部门')"
            @focus="getOptions1('客户部门')"
            placeholder="请选择"
            collapse-tags
            clearable
            filterable
            style="margin-left: 10px">
            <el-option
              v-for="item in cusDeptOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            >
            </el-option>
          </el-select>

      </div>
      <el-upload
        v-if="uploadPermission"
        class="upload-demo"
        :action="getActionUrl()"
        :before-upload="beforeUpload"
        :on-error="uploadFail"
        :on-success="uploadSuccess"
        :on-change="handleChange"
        :show-file-list="false"
        :headers="headers">
        <el-button round type="success">导入</el-button>
      </el-upload>
      <!-- <el-button type="warning" plain round  style="float: right; margin: 10px 0 10px 0;" @click="add()">增加协同管理者</el-button> -->
      <el-button type="primary" plain round v-if="permission" style="float: right; margin: 10px 0 10px 0;" @click="down()">导出</el-button>
    </el-row>
    <div>
      <el-table :data="tableData" border style="width: 100%" :header-cell-style="{ background: '#42b1e8', color: 'white' }" ref='multipleTable' max-height="500" v-loading="loading1" >

        <!-- <el-table-column align="center" prop="date" label="Deal ID" style="color: red" width="80" fixed="left">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit"><el-input v-model="scope.row.deal_id" clearable></el-input></span>
            <span v-else>{{ scope.row.deal_id }}</span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" prop="name" label="项目名称" width="120" fixed="left">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit"><el-input v-model="scope.row.project_name" clearable></el-input></span>
            <span v-else>{{ scope.row.project_name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="事业部" style="color: red" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-select
                @change="inputChange($event)"
                v-model="scope.row.dept_name"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.dept_name }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="主技术/产品中心" style="color: red" width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-select v-model="scope.row.core" placeholder="请选择">
                <el-option
                  v-for="item in optionsCore"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  @change="coreSearch($event)">
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.core }}</span>
          </template>
        </el-table-column>
        

        <el-table-column align="center" prop="name" label="销售" width="120">
         <template slot-scope="scope">
            <span v-if="scope.row.isEdit && scope.row.isAdd">
              <el-select
                  v-model="scope.row.xs_zh"
                  filterable
                  remote
                  clearable
                  placeholder="请输入"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @change="change(scope.$index,scope.row,$event,'销售')"
                  >
                  <el-option
                    v-for="item in options1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                  </el-option>
                </el-select>
            </span>
            <span v-else> {{ scope.row.xs_zh }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="客户部门" style="color: red" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.kh_dept }}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" align="center" label="客户经理">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-select
                  v-model="scope.row.am_zh"
                  filterable
                  clearable
                  remote
                  placeholder="请输入"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @change="change(scope.$index,scope.row,$event,'客户经理')"
                  >
                  <el-option
                    v-for="item in options1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                  </el-option>
                </el-select>
            </span>
            <span v-else> {{ scope.row.am_zh }}</span>
          </template>
        </el-table-column>

        <el-table-column width="120" align="center" label="项目经理">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-select
                  v-model="scope.row.pm_zh"
                  filterable
                  clearable
                  remote
                  placeholder="请输入"
                  :remote-method="remoteMethod"
                  :loading="loading"
                  @change="change(scope.$index, scope.row,$event,'项目经理')"
                  >
                  <el-option
                    v-for="item in options1"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                      <span style="float: left">{{ item.label }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                  </el-option>
                </el-select>
            </span>
            <span v-else>{{ scope.row.pm_zh }}</span>
          </template>
        </el-table-column>

        <el-table-column width="120" align="center" label="客户简称">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit"><el-input v-model="scope.row.kh_zh" clearable></el-input></span>
            <span v-else>{{ scope.row.kh_zh }}</span>
          </template>
        </el-table-column>

        <el-table-column width="120" align="center" label="市场区域">
          <template slot-scope="scope">
           <span v-if="scope.row.isEdit">
              <el-select
                @change="markChange($event)"
                v-model="scope.row.market_area"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in markOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.market_area }}</span>
          </template>
        </el-table-column>

        <el-table-column width="120" align="center" label="业务类型">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-select
                @change="businessChange($event)"
                v-model="scope.row.business_type"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in businessOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.business_type }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="产品分类" style="color: red" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-cascader
                v-model="scope.row.aa"
                :options="productionOptions"
                @change="change8($event)"
                clearable 
              >
              </el-cascader>
            </span>
            <span v-else>{{ scope.row.product_classification }}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" align="center" label="收入确认方式">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-select
                @change="incomeChange($event)"
                v-model="scope.row.revenue_recognition_method "
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in incomeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.revenue_recognition_method  }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="项目利润率(%)" style="color: red" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit"><el-input v-model="scope.row.project_profit_margin" clearable type="number"></el-input></span>
            <span v-else>{{ scope.row.project_profit_margin }}</span>
          </template>
        </el-table-column>
        <el-table-column width="120" align="center" label="正式项目/潜在项目概率">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-select v-model="scope.row.project_status" placeholder="请选择" clearable>
                <el-option
                  v-for="item in proOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.project_status }}</span>
          </template>
        </el-table-column>

        <el-table-column width="170" align="center" label="项目开始时间">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-date-picker
                v-model="scope.row.start_date"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width:140px">
              </el-date-picker>
            </span>
            <span v-if="!scope.row.from_pms && scope.row.start_date && scope.row.isNewEdit ">{{ toChange(scope.row.start_date , '-') }}</span>
            <span v-if="scope.row.from_pms">{{ scope.row.start_date }}</span>
          </template>
        </el-table-column>

        <el-table-column width="170" align="center" label="项目结束时间">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-date-picker
                v-model="scope.row.end_date"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width:140px">
              </el-date-picker>
            </span>
            <span v-if="!scope.row.from_pms && scope.row.end_date && scope.row.isNewEdit ">{{ toChange(scope.row.end_date , '-') }}</span>
            <span v-if="scope.row.from_pms">{{ scope.row.end_date }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="已归档合同金额" style="color: red" width="120">
          <template slot-scope="scope">
            <!-- <span v-if="scope.row.contract_amount_filed">{{ toThousands(Number(scope.row.contract_amount_filed)) | rounding}} </span> -->
            <span   v-if="scope.row.contract_amount_filed">{{toThousands(Number(scope.row.contract_amount_filed).toFixed(2))}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="合同状态" style="color: red" width="120">
          <template slot-scope="scope">
            <span>{{ scope.row.contract_status }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="是否有预算" style="color: red" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.isEdit">
              <el-select v-model="scope.row.is_budget" clearable placeholder="请选择">
                <el-option
                  v-for="item in optionsBudget"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.is_budget }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="是否定点" style="color: red" width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.isEdit">
              <el-select v-model="scope.row.is_point" clearable placeholder="请选择">
                <el-option
                  v-for="item in optionsBudget"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </span>
            <span v-else>{{ scope.row.is_point }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="合同计划签回时间" style="color: red" width="170">
          <template slot-scope="scope">
            <span v-if="scope.row.isEdit">
              <el-date-picker
                v-model="scope.row.contract_plan_time"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                style="width:140px">
              </el-date-picker>
            </span>
            <div v-else>
              <span v-if="!scope.row.from_pms && scope.row.contract_plan_time">{{ toChange(scope.row.contract_plan_time , '-') }}</span>
              <span v-else>{{ scope.row.contract_plan_time }}</span>
            </div>

          </template>
        </el-table-column>
        <el-table-column align="center" prop="date" label="项目总人月" style="color: red" width="100">
          <template slot-scope="scope">
            <span >{{ scope.row.project_total_person_month }}</span>
          </template>
        </el-table-column>
        <el-table-column width="150" align="center" label="项目预计总收入">
          <template slot-scope="scope">
            <span v-if="scope.row.isAdd && scope.row.isEdit">
              <el-input v-model="scope.row.estimate_income" type="number" clearable>
              </el-input>
            </span>
            <span v-else>{{ toThousands(scope.row.estimate_income ) }}</span>
          </template>
        </el-table-column>

        <el-table-column width="150" align="center" label="滚动预测总收入">
          <template slot-scope="scope">
            <span>{{ toThousands(scope.row.rolling_income ) }}</span>
          </template>
        </el-table-column>

        <el-table-column width="150" align="center" label="收入GAP">
          <template slot-scope="scope">
            <span>{{ toThousands(scope.row.GAP) }}</span>
          </template>
        </el-table-column>
        <el-table-column width="150" align="center" :label="val" v-for="(val,index) in income" :key="val+index+'A'">
          <template slot-scope="scope">
            <span v-if="scope.row.year_income">
               {{ toThousands(scope.row.year_income[index].value) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column width="150" align="center" :label="item" v-for="(item,index) in tableDataForecast" :key="index">
          <template slot-scope="scope">
            <div v-if="scope.row.from_pms && scope.row.forecast_data[index]">
              <el-input
                v-if="scope.row.isEdit && scope.row.forecast_data[index].has_permission"
                v-model="scope.row.forecast_data[index].value"
                type="number"
                clearable>
              </el-input>
              <div v-else>
                {{toThousands(scope.row.forecast_data[index].value)}}
              </div>
            </div>

            <div v-if="!scope.row.from_pms">
              <span v-if="scope.row.isAdd && scope.row.isEdit && item != 'YTD收入' && scope.row.forecast_data[index].has_permission">
                <el-input v-model="scope.row.forecast_data[index].value" type="number" clearable>
                </el-input>
              </span>
              <span v-else>{{ toThousands(scope.row.forecast_data[index].value) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="150" align="center" :label="item" v-for="(item,index) in monthPower" :key="index + 'B'">
          <template slot-scope="scope">
            <div v-if="scope.row.month_site_power">

            {{ scope.row.month_site_power[index].value }}
            </div>
          </template>
        </el-table-column>
        <el-table-column width="150" align="center" label="更新日志">
          <template slot-scope="scope">
            <div v-if="scope.row.up_user">
              <div v-if="scope.row.up_user.length>0" @click="showDetile(scope.$index,scope.row)" style="cursor:pointer">{{ scope.row.up_user[0].name }}</div>
            <div v-if="scope.row.up_user.length>0">{{ scope.row.up_user[0].time }}</div>
            </div>

          </template>
        </el-table-column>

        <el-table-column width="150" align="center" label="GAP说明">
          <template slot-scope="scope">
            <span>{{ scope.row.gap_desc }}</span>
          </template>
        </el-table-column>

        <el-table-column width="170" align="center" fixed="right" label="填写滚动预测">
          <template slot-scope="scope">
            <!-- 已存 -->
            <el-button type="danger" round size="mini" v-show="scope.row.from_pms && scope.row.showEdiBtn" @click="editFn(scope.$index,scope.row)" :disabled="!scope.row.can_edit">编辑</el-button>
            
            <el-button type="success" round size="mini" v-show="scope.row.isShow && scope.row.from_pms" @click="saveFn(scope.$index,scope.row)" style="margin-left: -20px;background-color: #46a6ff;border-color: #46a6ff;">保存</el-button>
            <el-button type="success" round size="mini" v-show="scope.row.isShow" @click.native.prevent="cancelFn(scope.$index,scope.row)" style="margin-left: 0px;background-color: #eda726;border-color: #eda726;">取消</el-button>

            <!-- 新增  -->
            <el-button type="success" round size="mini" v-show="!scope.row.from_pms && scope.row.isNewEdit" @click="newEditFn(scope.$index,scope.row)" style="margin-left: 0;" :disabled="!scope.row.can_edit">编辑</el-button>
            <el-button type="success" round size="mini" v-show="scope.row.isAdd && !scope.row.change " @click="newSaveFn(scope.$index,scope.row)" style="margin-left: 0;background-color: #46a6ff;border-color: #46a6ff">保存</el-button>

            <el-button type="warning" round size="mini" v-if="scope.row.isAdd && !scope.row.change " @click.native.prevent="deleteRow(scope.$index, tableData)" style="margin-left: 0px">取消</el-button>

            <el-button type="primary" round size="mini" v-show="!scope.row.from_pms && scope.row.isNewEdit" @click="deleteRow1(scope.$index, scope.row)" :disabled="!scope.row.can_delete" style="margin-left:-1px">删除</el-button>

            <el-button type="warning"  round size="mini" v-show="scope.row.change && !scope.row.isNewEdit" @click="newSaveFn1(scope.$index,scope.row)" style="margin-left: 0">保存</el-button>
            <el-button type="success" round size="mini" v-show="scope.row.change && !scope.row.isNewEdit" @click="cancelNewEdit(scope.$index,scope.row)" style="margin-left: 0px;background-color: #eda726;border-color: #eda726;">取消</el-button>

             <el-button type="success" style="background-color: #ce581394;border-color: #ce581394;margin-top:5px;margin-left:-1px" round size="mini" @click="shareProject(scope.$index, scope.row.project_id)" :disabled="!scope.row.can_share">协同维护</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        style="float: right; margin-top: 10px"
        @click="addFn()"
        v-if="showAddBtn" 
      >
      <!-- :disabled='!can_add' -->
        增加潜在项目
      </el-button>
      <el-pagination
        class="marT"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-size="baseSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        >
      </el-pagination>
    </div>
    <el-dialog title="提示" :visible.sync="dialogVisible" width="50%" :before-close="handleClose">
      <el-alert title="如果项目已经立项，请将潜在项目概率改为100%，将潜在项目与正式项目绑定。潜在项目数据将同步到正式项目，如果数据不是最近状况，请在正式项目更新。" type="warning" :closable="false"  effect="dark"></el-alert>
      <div style="margin:20px 0 20px 0">请选择一立项项目进行绑定 ：</div>
      <div>
        <el-select
          class="select"
          collapse-tags
          v-model="value2"
          filterable
          clearable
          placeholder="请选择项目"
          @change="handleChangedialogFn($event)"
        >
          <el-option
            v-for="item in dioOption"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          >
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleButton()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="dialogVisible1" width="30%" :before-close="handleClose">
      <div style="margin-bottom:10px">请填写GAP原因</div>
      <div>
        <el-input
          placeholder="请输入内容"
          v-model="gapDesc"
          clearable>
        </el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleButton1()">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="协同维护" :visible.sync="shareVisible" :getTableData="getTableData" width="60%" :destroy-on-close="true">
      <ShareDialog v-if="shareVisible" :shareId="String(shareId)"></ShareDialog>
    </el-dialog>
    <el-dialog title="更新日志" :visible.sync="dialogTableVisible" width='50%'>
    <el-table :data="gridData" border>
      <el-table-column  label="更新人员"  align='center'>
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column  label="更新时间" align='center'>
        <template slot-scope="scope">
          {{scope.row.time}}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        class="marT"
        background
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
        :current-page="current1"
        :page-size="baseSize1"
        layout="total, prev, pager, next, jumper"
        :total="total1"
        >
      </el-pagination>
</el-dialog>
  </div>
</template>

<script>

import Cookies from 'js-cookie';
import VTitle from '@/views/sys/internetThings/title';
import { mapState, mapMutations } from 'vuex';
import { getToken, getName, removeToken, removeName } from '@/utils/auth';
import http from '@/views/sys/axios';
import { Loading } from 'element-ui';
import { getHeader } from '@/app.config';
import shareDialog from './shareDialog'

export default {
  inject: ['reload'],
  name: 'CarPredictions',
  components: {
    VTitle,
    ShareDialog: shareDialog
  },
  data() {
    return {
      optionsCore:[
        {
          label:'爱普新思',
          value:'爱普新思',

        },
        {
          label:'智能汽车南京中心',
          value:'智能汽车南京中心',

        },
        {
          label:'智能汽车Kanzi设计中心',
          value:'智能汽车Kanzi设计中心',

        },
        {
          label:'沈阳分部',
          value:'沈阳分部',

        },
        {
          label:'智能汽车北京中心',
          value:'智能汽车北京中心',

        },
        {
          label:'智能汽车业务拓展部',
          value:'智能汽车业务拓展部',

        },
        {
          label:'智能汽车座舱产品中心',
          value:'智能汽车座舱产品中心',

        },
        {
          label:'智能汽车测试解决方案中心',
          value:'智能汽车测试解决方案中心',

        },
        {
          label:'大连分部',
          value:'大连分部',

        },
        {
          label:'智能汽车上海中心',
          value:'智能汽车上海中心',

        },
        {
          label:'智能汽车卓越事业部',
          value:'智能汽车卓越事业部',

        },
        {
          label:'智能汽车成渝中心',
          value:'智能汽车成渝中心',

        },
        {
          label:'智能汽车乌克兰中心',
          value:'智能汽车乌克兰中心',

        },
        {
          label:'智能汽车武汉中心',
          value:'智能汽车武汉中心',

        },
        {
          label:'其他（公共/售前项目类）',
          value:'其他（公共/售前项目类）',

        }],
      valueCore:'',
      indexParam:'',
      rowParam:{},
      indexParamNew:'',
      rowParamNew:{},
      showAddBtn:false,
      pradatas:{},
      Produnction:'',
      sale:'',
      cusDept:'',
      agreementStatus:'',
      costumeMg:'',
      ProdunctionOptions:[],
      saleOptions:[],
      cusDeptOptions:[],
      statusOptions:[],
      monthPower:[],
      proStatus:[],
      proClass:'',
      proClass1:'',
      productionOptions: [
        {
          value: "智能汽车产品",
          label: "智能汽车产品",
          children: [
            {
              value: "Kanzi & Kanzi Connect",
              label: "Kanzi & Kanzi Connect",
            },
            {
              value: "Auto Test Tool",
              label: "Auto Test Tool",
            },
            {
              value: "混合仪表固件",
              label: "混合仪表固件",
            },
            {
              value: "FOTA",
              label: "FOTA",
            },
            {
              value: "QNX Hypervisor",
              label: "QNX Hypervisor",
            },
            {
              value: "Others",
              label: "Others",
            },
          ],
        },
        {
          value: "智能汽车服务",
          label: "智能汽车服务",
          children: [
            {
              value: "智能驾驶舱软件开发服务",
              label: "智能驾驶舱软件开发服务",
            },
            {
              value: "IVI软件测试服务",
              label: "IVI软件测试服务",
            },
            {
              value: "Kanzi HMI//MW-开发服务",
              label: "Kanzi HMI//MW-开发服务",
            },
            {
              value: "Camera集成和Tuning",
              label: "Camera集成和Tuning",
            },
            {
              value: "语音语义集成服务",
              label: "语音语义集成服务",
            },
            {
              value: "Others",
              label: "Others",
            },
          ],
        },
        {
          value: "智能汽车方案",
          label: "智能汽车方案",
          children: [
            {
              value: "Android IVI",
              label: "Android IVI",
            },
            {
              value: "Hypervisor Cockpit",
              label: "Hypervisor Cockpit",
            },
            {
              value: "Linux IVI",
              label: "Linux IVI",
            },
            {
              value: "QNX Cluster",
              label: "QNX Cluster",
            },
            {
              value: "Info ADAS",
              label: "Info ADAS",
            },
            {
              value: "Audio",
              label: "Audio",
            },
            {
              value: "SRV",
              label: "SRV",
            },
            {
              value: "手机互联方案",
              label: "手机互联方案",
            },
            {
              value: "eAVB",
              label: "eAVB",
            },
            {
              value: "Others",
              label: "Others",
            },
          ],
        },
        // {
        //   value: "IOT",
        //   label: "IOT",
        //   children: [
        //     {
        //       value: "AR/VR",
        //       label: "AR/VR",
        //     },
        //     {
        //       value: "Camera",
        //       label: "Camera",
        //     },
        //     {
        //       value: "Cloud-FOTA",
        //       label: "Cloud-FOTA",
        //     },
        //     {
        //       value: "Cloud-MDM",
        //       label: "Cloud-MDM",
        //     },
        //     {
        //       value: "Face Access",
        //       label: "Face Access",
        //     },
        //     {
        //       value: "Handy Terminal",
        //       label: "Handy Terminal",
        //     },
        //     {
        //       value: "NB&mini-IOT",
        //       label: "NB&mini-IOT",
        //     },
        //     {
        //       value: "New Retailing",
        //       label: "New Retailing",
        //     },
        //     {
        //       value: "Robotics",
        //       label: "Robotics",
        //     },
        //     {
        //       value: "SmartHome",
        //       label: "SmartHome",
        //     },
        //     {
        //       value: "Smartspeaker",
        //       label: "Smartspeaker",
        //     },
        //     {
        //       value: "SOM",
        //       label: "SOM",
        //     },
        //     {
        //       value: "Wearable",
        //       label: "Wearable",
        //     },
        //     {
        //       value: "Others",
        //       label: "Others",
        //     },
        //   ],
        // },
        // {
        //   value: "Image/Graphics Algorithm",
        //   label: "Image/Graphics Algorithm",
        // },
        // {
        //   value: "Security",
        //   label: "Security",
        // },
        // {
        //   value: "Enterprise",
        //   label: "Enterprise",
        //   children: [
        //     {
        //       value: "MDM",
        //       label: "MDM",
        //     },
        //     {
        //       value: "FOTA",
        //       label: "FOTA",
        //     },
        //     {
        //       value: "APP开发",
        //       label: "APP开发",
        //     },
        //     {
        //       value: "智能系统",
        //       label: "智能系统",
        //     },
        //     {
        //       value: "En.-Others",
        //       label: "En.-Others",
        //     },
        //   ],
        // },
      ],
      value7:'',
      value6:'',
      optionsBudget:[
        {
          value:'是',
          label:'是'
        },{
          value:'否',
          label:'否'
        },
      ],
      income:[],
      xsIdap: '',
      xsZh: '',
      // business:'',
      businessOptions:[
        {
          value:'1',
          label:'软件开发/project'
        },{
          value:'2',
          label:'技术服务/FOTA'
        },{
          value:'3',
          label:'软硬一体'
        },{
          value:'4',
          label:'整体转包'
        },{
          value:'5',
          label:'软件代销'
        },{
          value:'6',
          label:'硬件设计'
        },{
          value:'7',
          label:'售后'
        },{
          value:'8',
          label:'IP'
        },{
          value:'9',
          label:'Royalty'
        },{
          value:'10',
          label:'硬件代销'
        },{
          value:'11',
          label:'产品' ,
          value:'12',
          label:'NRE'
        },{
          value:'13',
          label:'售前售后'
        },{
          value:'14',
          label:'售前'
        },{
          value:'15',
          label:'硬件销售'
        },{
          value:'16',
          label:'培训服务'
        }
      ],
      // income:'',
      incomeOptions:[
        {
          value:'1',
          label:'履约进度'
        },{
          value:'2',
          label:'商品销售'
        },{
          value:'3',
          label:'结算单'
        }
      ],
      mark:'',
      markOptions:[
        {
          value:'1',
          label:'中国大陆市场'
        },{
          value:'2',
          label:'中国台湾市场'
        },{
          value:'3',
          label:'马来西亚市场'
        },{
          value:'4',
          label:'印度市场'
        },{
          value:'5',
          label:'亚洲其他市场'
        },{
          value:'6',
          label:'日本市场'
        },{
          value:'7',
          label:'韩国市场'
        },{
          value:'8',
          label:'欧洲市场'
        },{
          value:'9',
          label:'北美市场'
        },{
          value:'10',
          label:'其他'
        }
      ],
      oldEdit:false,
      newParams:{},
      par_project_id:'',
      shareVisible:false,
      isSave:false,
      gapDesc:'',
      dialogVisible1:false,
      amZh:'',
      pmZh:'',
      pmIdap:[],
      amIdap:[],
      xs_zh:'',
      xs_ldap:[],
      cache:[],
      options1:[],
      proIdListArr:[],
      props: { multiple: true },
      selected: null,
      selector: [],
      num:'',
      detId:'',
      headers: getHeader(),
      permission:false,
      uploadPermission:false,
      rowData:{},
      dialogVisible: false,
      tmpV:[],
      proOptions: [{
          value: '30%',
          label: '30%'
        },{
          value: '50%',
          label: '50%'
        }, {
          value: '80%',
          label: '80%'
        }, {
          value: '100%',
          label: '100%'
        }],
      val:'',
      value:'',
      saveLabel:'',
      saveValue:[],
      current:1,
      current1:1,
      baseSize: 10,
      baseSize1: 10,
      total: 0,
      total1: 0,
      isAdd:false,
      input: '',
      loading: false,
      loading1: false,
      tableData: [],
      tableDataForecast:[],
      projectsId: [],
      projectsId1: [],
      dept_id: [],
      cosName:'客户简称',
      proStatus:[],
      status: 1,
      token: getToken(),
      userName: getName(),
      props: { multiple: true },
      value2: [],
      cusNames: [],
      options: [],
      dioOption:'',
      dioDatas:{},
      rollDataId:'',
      cusNamesOptions: [],
      shareId: '',
      can_add: false,
      can_edit: false,
      can_collaborate: false,
      can_delete: false,
      gridData:[],
      dialogTableVisible:false,
      paramsProId:'',
      saveProject:[],
      saveChance:[],
      saveVal: [],
      saveType: '',
    };
  },
  created() {
    this.getOptionsResult()
  },
  mounted() {
    this.getTableData()
    this.proStatusFn()
    this.dioPro()
    this.init()
  },
  filters: {
    rounding (value) {
      if(value || value === 0) { //这个判断是为了防止数据为空，页面渲染为NAN
        return Number(value).toFixed(2)
      }
    }
  },
  methods: {
    coreSearch(e){
      console.log(e)
    },
    getOptions1(val){
      let data = {}
      data['name'] = val
      http.post(`/api/data_summary/car/roll/condition`,data)
      .then((res => {
        if(res.code === 200){
          this.ProdunctionOptions = res.msg
          this.saleOptions = res.msg
          this.cusDeptOptions = res.msg
          this.statusOptions= res.msg
        }
      }))
    },
    filterData(val,type){
      this.saveVal = val
      this.saveType = type
      if(type == '主技术中心/主产品中心'){ this.pradatas.core = val}
      if(type == '销售'){ this.pradatas.xs_zh = val}
      if(type == '客户部门'){ this.pradatas.kh_dept = val}
      if(type == '合同状态'){ this.pradatas.contract_status = val}
      if(type == '客户经理'){ this.pradatas.am = val}
      this.tableDataForecast = []
      this.current = 1
      this.getTableData()
    },
    change8(e){
      e.length>0?this.proClass =  `${e[0]} / ${e[1]}`:this.proClass=''
    },
    businessChange(val){
      // console.log(77,val)
    },
    incomeChange(v){
      // console.log(66,v)
    },
    markChange(e){
      // console.log(55,e)
    },
    add(){
      this.shareVisible = true
    },
    deleteRow1(index, row) {
      http.get(`/api/data_summary/car/roll/delete_project?project_id=${row.project_id}`)
      .then(res => {
        if(res.code === 200){
          this.$message({
            message: "删除成功",
            type: 'success',
          });
          this.reload()
        }else{
          //  this.$message({
          //   message: res.msg,
          //   type: 'error',
          // });
        }
      })
    },
    generate(arr) {
      if(arr) {
        const list = arr.map(item => item.label)
        return list
      } else {
        return []
      }
    },
    change(index,row,val,type) {
      if(type=="客户经理"){
        this.cache.map(item =>{
          if(item.value == val) {
            row.am_ldap = val
            row.am_zh = item.label
          }
        })
      }
      if(type=="销售"){
        this.cache.map(item =>{
          if(item.value == val) {
           row.xs_ldap = val
           row.xs_zh = item.label
          }
        })
      }
      if(type=='项目经理'){
        this.cache.map(item =>{
            if(item.value == val) {
              row.pm_ldap = val
              row.pm_zh = item.label
            }
        })
      }
      this.$set(this.tableData,index,row)
    },
    generate(arr) {
      if(arr) {
        const list = arr.map(item => item.label)
        return list
      } else {
        return []
      }
    },
    blur() {
      this.options1 = []
    },
     remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        this.options1 = []
        this.getStateResult(query)
      } else {
        this.options1 = []
      }
    },
    getStates(name) {
      return http.get(`/api/account/user/query?name=${name}`)
    },
    async getStateResult(name) {
      try {
        const { code, user_list } = await this.getStates(name)
        if(code === 200) {
          this.loading = false
          this.options1 = user_list
          this.cache = user_list
        }
      } catch (err) {
        throw new Error(err)
      }
    },
    changeProject(val) {
      this.saveProject = val
      this.tableDataForecast = []
      //this.income = []
      this.monthPower = []
      this.current = 1
      let proIdList = []
      val.forEach(item => {
          proIdList.push(item[2])
      })
      this.proIdListArr = proIdList
      this.getTableData()
      let arr = this.selector
    },
    getOptions() {
        return http.get(`/api/data_summary/car/roll/list_tree`)
      },
      async getOptionsResult() {
        try {
          const { code, project_list } = await this.getOptions()
          if(code === 200) {
            this.selector = project_list
          }
        } catch (err) {
          throw new Error(err)
        }
      },
    toChange(str,fomit){
      var arr = str.split(fomit);
      return arr[0]+'年'+arr[1]+'月'+arr[2]+'日'
      },
    toThousands(num1) {
      num1 = (num1 || 0).toString();
      let number = 0,
          floatNum = '',
          intNum = '';

      if (num1.indexOf('.') > 0) {
        number = num1.indexOf('.')
        floatNum = num1.substr(number)
        intNum = num1.substring(0,number)
      } else {
        intNum = num1;
      }
      let result = [],
          counter = 0;
      intNum = intNum.split('');

      for (let i = intNum.length - 1; i >= 0; i--) {
        counter++;
        result.unshift(intNum[i]);
        if (!(counter % 3) && i != 0) { result.unshift(','); }
      }
      return result.join('') + floatNum || '';
    },
    getActionUrl() {
			return (`${process.env.VUE_APP_KANBAN_HOST}/api/data_summary/car/roll/up_datas`)
		},
    beforeUpload(file) {
      let extension = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isExcel = extension == "xlsx" || extension == "xls" || extension == "csv"
      this.loading = true
			if (!isExcel) {
				this.$message.warning("文件格式不对（只支持.xlsx|.xls|.csv文件）");
			}
		},
		handleChange(file, fileList) {
      this.fileList = fileList;
		},
    uploadFail() {
      var self = this
			self.loading = false
			self.$message.error('上传失败')
		},
    uploadSuccess(res) {
      var self = this
      self.loading = false
      if (res.code === 200) {
        this.$message({
          message: "导入成功",
          type: 'success',
        });
        location.reload()
      }if(res.code === 400){
        this.$message({
            message: '导入内容不正确',
            type: 'error'
          });
      }
		},
    dioPro(){
      http.get(`/api/data_summary/car/department/list?status=2`)
        .then((res) => {
          if (res.code === 200) {
            this.dioOption = res.msg;
            }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    handleChangedialogFn(e){
      this.dioOption.forEach(item =>{
        if(e.indexOf(item.label)>-1){
         this.projectsId1 = item.value
        }
      })
      this.rowData.project_id = this.projectsId1
      this.rowData.roll_data_id = this.rollDataId
      this.rowData.dept_id = this.detId || this.num
    },
    dialogVisibleButton(){
      http.post(`/api/data_summary/car/roll/transferprojectdata`,this.rowData)
      .then((res) =>{
        const { code,datas,count} = res
        if(res.code === 200){
          this.$message({
             message: '保存成功',
              type: 'success',
          })
        }
      })
      // this.dialogVisible = false
      this.reload()
    },
    handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
    inputChange(e){
      this.options.forEach(item =>{
        if(e.indexOf(item.label)>-1){
          this.detId = item.value
        }
      })
    },
    dialogVisibleButton1(){
      if( this.oldEdit ) {  // 已存项目编辑保存
        let obj = {}
        let obj1 = {}
        let obj2 = {}
        let obj3 = {}
        obj['name'] = 'gapDesc'
        obj['value'] = this.gapDesc
        obj['project_id'] = this.rollDataId
        this.newParams.push(obj)

        obj1['name'] = 'xs_zh'
        obj1['value'] = this.xsZh
        obj1['project_id'] = this.rollDataId
        this.newParams.push(obj1)

        obj2['name'] = 'xs_ldap'
        obj2['value'] = this.xsIdap
        obj2['project_id'] = this.rollDataId
        this.newParams.push(obj2)

        obj3['name'] = 'market_area'
        obj3['value'] = this.mark
        obj3['project_id'] = this.rollDataId
        this.newParams.push(obj3)
        http.post(`/api/data_summary/car/roll/up_data`,this.newParams)
        .then((res => {
          if(res.code === 200) {
             if(this.saveProject){ this.changeProject(this.saveProject)}
            //  if(this.saveChance){ this.handleChange3(this.saveChance) }
            // if(this.saveType){this.filterData(this.saveVal,this.saveType)}
            this.$message({type:'success',message:"保存成功!"})
            this.$set(this.tableData,this.indexParam,this.rowParam)
          }else{this.$message({ type:'error',message:"保存失败!"})}
        }))
      } else if( !this.oldEdit || isAdd && change) {
        this.newParams['gapDesc'] = this.gapDesc
        this.newParams['dept_id'] = this.detId || this.num
        http.post(`/api/data_summary/car/roll/rotentialprojectdata`,this.newParams)
        .then((res => {
          if(res.code === 200){
            if(this.saveProject){ this.changeProject(this.saveProject)}
            // if(this.saveChance){ this.handleChange3(this.saveChance) }
            // if(this.saveType){this.filterData(this.saveVal,this.saveType)}
            this.$message({type:'success',message:"保存成功!"})
            this.$set(this.tableData,this.indexParamNew,this.rowParamNew)
          }else{this.$message({ type:'error',message:"保存失败!"})}
        }))
      }
      this.dialogVisible1 = false
    },
    newSaveFn1(index,row){
      this.indexParamNew = index
      this.rowParamNew = row
      row.product_classification = this.proClass
      if(row.contract_plan_time) row.contract_plan_time = row.contract_plan_time.replace(/[^\d]/g,'-')
      if(!row.project_name || !row.dept_name){
        this.$message({
              message: '项目名或事业部不能为空',
              type: 'error',
            });
        return false
      }
       if((row.project_status ==="50%" && !row.start_date) || (row.project_status ==="80%" && !row.start_date) || (row.project_status ==="100%" && !row.start_date)){
        this.$message.error("请先选择项目开始时间");
        return
      }
      if((row.project_status ==="50%" && !row.end_date) || (row.project_status ==="80%" && !row.end_date) || (row.project_status ==="100%" && !row.end_date)){
        this.$message.error("请先选择项目结束时间");
        return
      }
      if(!row.is_budget){
        this.$message.error("请先选择是否有预算");
        return
      }
      if(!row.is_point){
        this.$message.error("请先选择是否定点");
        return
      }
      if(!row.contract_plan_time){
        this.$message.error("请先选择合同计划签回时间");
        return
      }
      if(!row.project_profit_margin){
        this.$message.error("请先选择项目利润率");
        return
      }
      if(!row.business_type){
        this.$message.error("请先选择业务类型");
        return
      }
      if(!row.market_area){
        this.$message.error("请先选择市场区域");
        return
      }
      if(!row.product_classification){
        this.$message.error("请先选择产品分类");
        return
      }
      if(!row.kh_zh){
        this.$message.error("请先选择客户简称");
        return
      }
      if(!row.am_zh){
        this.$message.error("请先选择客户经理");
        return
      }
      if(!row.xs_zh){
        this.$message.error("请先选择销售");
        return
      }
      if(!row.project_status){
        this.$message.error("请先选择正式项目/潜在项目概率");
        return
      }
      let sum = 0
      row.forecast_data.map((val,ind) => {
        sum += Number(val.value)
      })
      let result = 0
      result = row.estimate_income - sum
      if( result < 0 && !this.isSave && row.project_status !== "100%"){
        this.dialogVisible1 = true
        row.change = true
        row.isNewEdit = true
        row.isAdd = false
        row.dept_id = this.num
        row.isShow = false
        row.project_id = this.rollDataId
        this.newParams = row
        return
      }
      if(row.project_status === "100%"){
        this.dialogVisible = true
        this.dioPro()
      } else {
      row.change = true
      row.isAdd = false
      row.isShow = false
      row.isNewEdit = true
      row.dept_id =  this.detId || this.num 
      row.project_id = this.rollDataId
      let data = row
      http.post(`/api/data_summary/car/roll/rotentialprojectdata`,data)
      .then((res) => {
        const {data, code } = res
          if(code === 200) {
            this.changeProject(this.saveProject)
            this.getOptionsResult()
            this.$message({
                message: '保存成功!',
                type: 'success',
              });
          }else{
            this.$message({
                message: '保存失败!',
                type: 'error',
              });
          }
      })
     }
     if(row.project_status !== "100%"){
      //  this.reload()
     }
      this.$set(this.$refs.multipleTable.tableData,index,row)
    },
    newEditFn(index,row){
      this.proClass = row.product_classification
      this.gapDesc = row.gap_desc
      this.newParams = row
      this.num = row.dept_id
      this.rowData = row
      this.rollDataId = row.project_id
      row.isNewEdit = false
      row.isAdd = true
      row.change = true
      row.isEdit = true
      this.$set(this.tableData,index,row)
    },
    newSaveFn(index,row){
      row.product_classification = this.proClass
      let data = row
      if(!data.project_name){
        this.$message.error('项目名不能为空');
        return false
      }
      if(!this.detId){
        this.$message.error('事业部不能为空');
        return false
      }
      if(!row.xs_zh){
        this.$message.error("请先选择销售");
        return
      }
      if(!row.am_zh){
        this.$message.error("请先选择客户经理");
        return
      }
      if(!row.kh_zh){
        this.$message.error("请先选择客户简称");
        return
      }
      if(!row.market_area){
        this.$message.error("请先选择市场区域");
        return
      }
      if(!row.business_type){
        this.$message.error("请先选择业务类型");
        return
      }
      if(!row.product_classification){
        this.$message.error("请先选择产品分类");
        return
      }
      if(!row.project_profit_margin){
        this.$message.error("请先选择项目利润率");
        return
      }
      if((row.project_status ==="50%" && !row.start_date) || (row.project_status ==="80%" && !row.start_date) || (row.project_status ==="100%" && !row.start_date)){
        this.$message.error("请先选择项目开始时间");
        return
      }
      if((row.project_status ==="50%" && !row.end_date) || (row.project_status ==="80%" && !row.end_date) || (row.project_status ==="100%" && !row.end_date)){
        this.$message.error("请先选择项目结束时间");
        return
      }
      if(!row.is_budget){
        this.$message.error("请先选择是否有预算");
        return
      }
      if(!row.is_point){
        this.$message.error("请先选择是否定点");
        return
      }
      if(!row.contract_plan_time){
        this.$message.error("请先选择合同计划签回时间");
        return
      }
      let sum1 = 0
      row.forecast_data.map((val,ind) => {
        sum1 += Number(val.value)
      })
      let result = 0
      result = row.estimate_income - sum1
      if( result < 0 && !this.isSave && row.project_status !== "100%"){
        this.dialogVisible1 = true
        row.isNewEdit = true
        row.isAdd = false
        row.isShow = false
        row.isEdit = false
        row.dept_id = this.detId
        row.project_id = this.par_project_id
        this.newParams = row
        return
      }
      if(row.project_status === "100%"){
        this.dialogVisible = true
        row.dept_id = this.detId
        this.rowData = row
        this.dioPro()
      } else {
        row.isNewEdit 
        row.isAdd = false
        row.isNewEdit = true
        row.isShow = false
        row.isEdit = false
        row.dept_id =  this.detId || this.num
        row.project_id = this.par_project_id
        data = row
        this.newParams = row
        http.post(`/api/data_summary/car/roll/rotentialprojectdata`,data)
        .then((res) => {
          const {data, code } = res
            if(code === 200 && row.project_status !== "100%") {
              this.changeProject(this.saveProject)
              this.getOptionsResult()
              this.$message({
                  message: '保存成功',
                  type: 'success',
                });
                this.$set(this.tableData,index,row)
            }if(code === 400){
              this.deleteRow(index, this.tableData)
            }
        })
      }
    },
    handleCurrentChange(val) {
      this.current = val;
      this.tableDataForecast = []
      //this.income = []
      this.monthPower = []
      this.getTableData()
    },
    handleCurrentChange1(val) {
      this.current1 = val;
      this.gridData = []
      http.get(`/api/data_summary/car/roll/GetUpdateRecord?project_id=${this.paramsProId}&page=${this.current1}`)
      .then(res => {
        if(res.code === 200){
          this.gridData = res.data
          this.total1= res.count || 0
        }
      })
    },
    handleSizeChange(val){
    },
    handleSizeChange1(val){
    },
    init() {
      http.get(`/api/data_summary/car/department/list`)
        .then((res) => {
          if (res.code === 200) {
            this.options = res.msg.children;
          } else if (res.data.code == 401) {
            removeToken();
            removeName();
            this.$message.error('登陆超时或该账号已被登出，请您重新登录');
            this.$router.push({
              path: '/#/login',
            });
          } else {
            console.log('无数据');
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    proStatusFn() {
     http.get(`/api/data_summary/car/roll/status`)
        .then((res) => {
          if (res.code === 200) {
            this.cusNamesOptions = res.msg;
            } else if (res.data.code == 401) {
              removeToken();
              removeName();
              this.$message.error('登陆超时或该账号已被登出，请您重新登录');
              this.$router.push({
                path: '/#/login',
              });
          } else {
            console.log('无数据');
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    getTableData(){
      this.loading1 = true
      this.pradatas.projects = this.proIdListArr
      this.pradatas.status = this.proStatus
      this.pradatas.page = this.current
      http.post(`/api/data_summary/car/roll/data`,this.pradatas)
      .then((res) =>{
        const { count,is_xs_or_am, is_pm, is_collaboration } = res
        if(res.code === 200){
          this.monthPower = []
          this.loading1 = false
          this.permission = res.download_permission
          this.showAddBtn= res.add_potential_permission
          this.uploadPermission = res.updata_permission
          let arrTmp = []
          let arrTmp1 = []
          let arrTmp2 = []
          res.result.forEach(item=>{
            item.aa=item.product_classification.split(' / ')
          })
          this.tableData=[]
          this.tableData = res.result
          if (is_xs_or_am) {
            this.can_add = true
            this.can_edit = true
            this.can_collaborate = true
            this.can_delete = false
          } else {
            if (is_pm) {
              this.can_edit = false
              this.can_add = false
              this.can_collaborate = false
              this.can_delete = false
            } else if (is_collaboration) {
              this.can_edit = true
              this.can_add = false
              this.can_delete = false
              this.can_collaborate = false
            }
          }
          
          this.tableData.forEach(item => {
            arrTmp = item.forecast_data
            arrTmp1 = item.year_income
            arrTmp2 = item.month_site_power
            item.isShow = false
            item.isEdit = false
            item.isNewEdit = true
            item.showEdiBtn = true
            item.isAdd = false
            this.amZh = item.am_zh
            this.pmZh = item.pm_zh
            this.xs_zh = item.xs_zh
            this.xs_ldap = item.xs_ldap
            this.amIdap = item.am_ldap
            this.pmIdap = item.pm_ldap
            if (is_collaboration) {
              item.collaborationDisabled = !item.from_pms
            }
          })
          this.tableDataForecast = []
          arrTmp.forEach(item => {
            this.tableDataForecast.push(item.label)
          })
          this.income = []
          arrTmp1.forEach(val => {
            this.income.push(val.label)
          })
          
          arrTmp2.forEach(value => {
            this.monthPower.push(value.label)
          })
          this.tmpV = arrTmp
          this.total = count || 0

        }else{
          this.loading1 = false
        }
      })
    },
    handleChange3(e) {
      this.saveChance = e
      this.tableDataForecast = []
      this.income = []
      this.monthPower = []
      this.current = 1
      let arr = []
      for(var i=0; i<e.length;i++){
        arr.push(e[i])
      }
      this.proStatus = arr
      this.getTableData()
    },
    down(){
      this.loading = true
      http.get(`/api/data_summary/car/roll/download_template`,{ responseType: 'blob' })
      .then((res) => {
          const { data, code } = res;
          if (code === 200) {
            let blob = new Blob([data], { type: 'application/vnd.ms-excel' })
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', '滚动预测报表.xlsx');
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
            this.loading = false
            this.$message.success('导出成功!');
          } else {
            this.$message.error('下载出错了!');
          }
        })
        .catch((err) => {
          const { data } = err;
          if (data) {
            let blob = new Blob([data], { type: 'application/vnd.ms-excel' });
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = URL.createObjectURL(blob);
            link.setAttribute('download', '滚动预测报表.xlsx');
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
            this.loading = false
            this.$message.success('导出成功!');
          } else {
            this.$message.error('下载出错了!');
            this.loading = false
          }
        })
    },
    deleteRow(index, rows) {
      rows.splice(index, 1)
    },
    saveFn(index,row){
      if((row.contract_status == '合同部分归档' || row.contract_status == '无合同') && !row.is_budget){
        this.$message.warning("请先选择是否有预算");
        return
      }
      if((row.contract_status == '合同部分归档' || row.contract_status == '无合同') && !row.is_point){
        this.$message.warning("请先选择是否定点");
        return
      }
      if(!row.contract_plan_time && (row.contract_status=="无合同" || row.contract_status=="合同部分归档" )){
        this.$message.warning("请先选择合同计划签回时间");
        return
      }
      this.mark = row.market_area
      this.gapDesc = row.gap_desc
      this.rollDataId = row.project_id
      this.xsZh = row.xs_zh
      this.xsIdap = row.xs_ldap
      row.isShow = false
      row.isEdit = false
      row.showEdiBtn = true
      let list = []
      let obj = {}
      let obj1 = {}
      let obj2 = {}
      let obj3 = {}
      let obj4 = {}
      let obj5 = {}
      let obj6 = {}
      obj['name'] = 'gapDesc'
      obj['value'] = row.gap_desc
      obj['project_id'] = row.project_id
      list.push(obj)

      obj1['name'] = 'xs_zh'
      obj1['value'] = row.xs_zh
      obj1['project_id'] = row.project_id
      list.push(obj1)

      obj2['name'] = 'xs_ldap'
      obj2['value'] = row.xs_ldap
      obj2['project_id'] = row.project_id
      list.push(obj2)

      obj3['name'] = 'market_area'
      obj3['value'] = row.market_area
      obj3['project_id'] = row.project_id
      list.push(obj3)

      obj4['name'] = 'is_budget'
      obj4['value'] = row.is_budget
      obj4['project_id'] = row.project_id
      list.push(obj4)

      obj5['name'] = 'is_point'
      obj5['value'] = row.is_point
      obj5['project_id'] = row.project_id
      list.push(obj5)

      obj6['name'] = 'contract_plan_time'
      obj6['value'] = row.contract_plan_time
      obj6['project_id'] = row.project_id
      list.push(obj6)

      let sum = 0
      row.forecast_data.map((val,ind) => {
        sum += Number(val.value)
      })
      let result = 0
      result = row.estimate_income - sum
      row.forecast_data.forEach(item => {
        if(item.has_permission) {
          let v = {}
          v.name = item.label
          v.value = item.value
          v.project_id = row.project_id
          list.push(v)
        }
      })
      if( result < 0){
        this.dialogVisible1 = true
        this.newParams = list
        return
      }
      this.indexParam = index
      this.rowParam = row
      http.post(`/api/data_summary/car/roll/up_data`,list)
      .then((res => {
         if(res.code === 200) {
           if(this.saveProject){ this.changeProject(this.saveProject)}
          //  if(this.saveChance){ this.handleChange3(this.saveChance) }
           if(this.saveType){this.filterData(this.saveVal,this.saveType)}
          this.$set(this.tableData,index,row)
           this.$message({
             type:'success',
             message:"保存成功!"
           })
         }else{
           this.$message({
             type:'error',
             message:"保存失败!"
           })
         }
      }))
    },
    addFn() {
      this.newAdd = true
      let tmpVal = []
      this.tmpV.forEach(item => {
        tmpVal.push({
          value:'',
          label:item.label,
          has_permission:item.has_permission,
        })
      })
      this.tableData.push({
        isNewEdit:false,
        from_pms:false,
        newEdit:false,
        isEdit: true,
        isAdd:true,
        estimate_income:'0',
        forecast_data:tmpVal
      })
    },
    editFn(index,row){
      this.gapDesc = row.gap_desc
      this.oldEdit = row.from_pms
      row.showEdiBtn = false
      row.isShow = true
      row.isEdit = true
      this.rollDataId = row.project_id
      this.$set(this.tableData,index,row)
    },
    cancelNewEdit(index,row){
      row.isNewEdit = true
      row.isAdd = false
      if(this.saveProject){ this.changeProject(this.saveProject)}
    },
    cancelFn(index,row){
      row.showEdiBtn = true
      row.isNewEdit = true
      row.isEdit = false
      row.isShow = false
      this.$set(this.tableData,index,row)
    },
     shareProject(index, id) {
      this.shareId = id
      this.shareVisible = true
    },
    showDetile(index,row){
      this.dialogTableVisible = true
      let datas = {}
      // datas.page = this.current1
      // datas.project_id = row.project_id
      this.paramsProId = row.project_id
      http.get(`/api/data_summary/car/roll/GetUpdateRecord?project_id=${row.project_id}&page=${this.current1}`)
      .then(res => {
        if(res.code === 200){
          this.gridData = res.data
          this.total1= res.count || 0
        }
      })
    }
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-table th.gutter{
  display: table-cell!important;
}
#cascader, #selectd{
    margin: auto 0;
    width: 20%;
    &.mwidth{
    width: 23%;
    }
}
.det{
  display: inline !important
}
#carPredition {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
  .btn-group {
    position: relative;
    .edit {
      position: absolute;
      top: 50%;
      right: -2%;
      transform: translate(-50%, -50%);
    }
  }
}
.upload-demo{
  float: right;
  margin-bottom: 10px;
  margin-top: 10px

}
.marT{
  margin-top:10px ;
}
.marFlex[data-v-628ad97d] {
  /* margin: auto; */
  margin-top: 15px;
}
.group-width {
  display: flex;
  flex-wrap: nowrap;
}
.mar-l {
  margin-left: 30px;
}
.mar-row {
  margin-bottom: 30px;
}
.select {
  width: 150px;
  display: inline-block !important
}
.border {
  box-sizing: content-box;
  height: 0;
  overflow: visible;
  margin-top: 1rem;
  margin-bottom: 1rem;
  border: 0;
  border-top: 1px solid rgba(0, 0, 0, 0.1);
}
.form-control {
  background-color: #ffffff;
  background-image: none;
  border: 1px solid #e5e6e7;
  border-radius: 1px;
  color: inherit;
  display: block;
  padding: 6px 12px;
  transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
  width: 100%;
  font-size: 0.9rem;
  box-shadow: none;
}
label {
  color: rgb(103, 106, 108);
  font-weight: normal;
}
.mr-1,
.mx-1 {
  margin-right: 1.58rem;
  margin-left: 2.1rem;
  /* padding-left: 2rem; */
}
.ml-3,
.mx-3 {
  margin-left: 1rem !important;
}
.mr-4 {
  width: 40%;
}
.ml-2 {
  float: right;
  margin-right: 4%;
}
.col-form-label {
  padding-top: calc(0.375rem + 1px);
  padding-bottom: calc(0.375rem + 1px);
  margin-bottom: 0;
  font-size: inherit;
  line-height: 1.5;
  font-size: 15px;
}
label {
  display: inline-block;
  margin-bottom: 0.5rem;
}
.cancelFlex,
.cancelFlexDepart {
  margin: auto 15px;
}
.cell-grey {
  background: red;
}
.el-table .warning-row {
  background: grey;
}
#preWrite {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;
  .btn-group {
    text-align: right;
  }
  .table {
    overflow-x: auto;
    .flexTable {
      display: table-cell;
      position: relative;
      .span {
        cursor: pointer;
      }
    }
    .wordWrap {
      text-overflow: -o-ellipsis-lastline;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 1;
      line-clamp: 1;
      -webkit-box-orient: vertical;
    }
  }
}
@media screen and (max-width: 1440px){
        #group .bgColor .toFlex .item #cascader.mwidth{
        width: 25%;
        }
    }
</style>
